<?php

/**
 * Description of Updater
 *
 * @author NE
 */
class RCMS_Object_Updater_Updater {

	const UPDATER_SUCCESS = 'success';

	const UPDATER_FAIL = 'fail';

	protected $_seoParser = null;

	protected $_model = null;

	protected $_websiteUrl = '';

	protected $_websitePath = '';

	public function  __construct() {
		$this->_model = new RCMS_Object_Updater_UpdaterModel();
		$this->_seoParser = new RCMS_Object_Parser_SeoParser();
		$this->_websiteUrl = unserialize(Zend_Registry::get('config'))->website->website->url;
		$this->_websitePath = unserialize(Zend_Registry::get('config'))->website->website->path;
	}

	public function updatePages($pages) {
		foreach ($pages as $page) {
			$rcmcatPage = new RCMS_Object_Page_Page(intval($page->rcms_pid));
			$oldPgUrl = $rcmcatPage->getUrl();
			$rcmcatPage->setNavName($page->navigationTitle);
			$rcmcatPage->setH1Tag($page->headerTitle);
			$rcmcatPage->setHeaderTitle($page->pageTitle);
			$rcmcatPage->setMetaDescription($page->metaDescription);
			$rcmcatPage->setMetaKeywords($page->metaKeywords);
			$rcmcatPage->setShortDescription($page->description);
			$rcmcatPage->setBestPractices($page->useSeorule);
			$rcmcatPage->setUrl($page->url);
			$rcmcatPage->setSeosambaRuleId($page->ruleId);
			$catSaveResult = $rcmcatPage->save();

			//doing needed sync
			$this->_seoParser->chainSyncOnUpdate($oldPgUrl, $page->url, $rcmcatPage->getH1Tag(), $rcmcatPage->getId());
			$this->_seoParser->createSiteMapFile();
			if(isset($page->pages)) {
				foreach ($page->pages as $regPage) {
					$rcmsregPage = new RCMS_Object_Page_Page(intval($regPage->rcms_pid));
					$oldRegPgUrl = $rcmsregPage->getUrl();
					$rcmsregPage->setNavName($regPage->navigationTitle);
					$rcmsregPage->setH1Tag($regPage->headerTitle);
					$rcmsregPage->setHeaderTitle($regPage->pageTitle);
					$rcmsregPage->setMetaDescription($regPage->metaDescription);
					$rcmsregPage->setMetaKeywords($regPage->metaKeywords);
					$rcmsregPage->setShortDescription($regPage->description);
					$rcmsregPage->setBestPractices($regPage->useSeorule);
					$rcmsregPage->setUrl($regPage->url);
					$rcmsregPage->setSeosambaRuleId($regPage->ruleId);
					$regSaveResult = $rcmsregPage->save();
					$this->_seoParser->chainSyncOnUpdate($oldRegPgUrl, $regPage->url, $rcmsregPage->getH1Tag(), $rcmsregPage->getId());
					$this->_seoParser->createSiteMapFile();
				}
			}
		}
		if($catSaveResult && $regSaveResult) {
			return true;
		}
		return false;
	}


	public function updateDeeplinks($deeplinks) {
		if(empty($deeplinks)) {
			return self::UPDATER_SUCCESS;
		}
		$deeplinksIds = $this->_model->getDeeplinksIds();
		if(!empty ($deeplinksIds)) {
			foreach ($deeplinksIds as $deeplinkId) {
				$this->_seoParser->deleteDeeplinkFromContent($deeplinkId);
			}
		}
		$this->_model->cleanDeeplinks();
		foreach ($deeplinks as $deeplink) {
			$rcmsDeeplink = new RCMS_Object_Deeplink_Deeplink();
			$rcmsDeeplink->setName($deeplink->name);
			$deeplinkType = ($deeplink->type == 'ext') ? RCMS_Object_Deeplink_Deeplink::TYPE_EXTERNAL : RCMS_Object_Deeplink_Deeplink::TYPE_INTERNAL;
			$rcmsDeeplink->setType($deeplinkType);
			$deeplinkUrl = ($rcmsDeeplink->getType() == RCMS_Object_Deeplink_Deeplink::TYPE_INTERNAL) ? $deeplink->websiteUrl . $deeplink->pageUrl . '.html' : $deeplink->url;
			$rcmsDeeplink->setUrl($deeplinkUrl);
			$rcmsDeeplink->setNoFollow(($rcmsDeeplink->getType() == RCMS_Object_Deeplink_Deeplink::TYPE_EXTERNAL) ? 1 : 0);
			$rcmsDeeplink->setBan(0);
			$rcmsDeeplink->setExtWebsiteId($deeplink->extWebsiteId);
			$saveResult = $rcmsDeeplink->save();
		}
		if($saveResult) {
			$this->_seoParser->replaceDeeplinksInContent();
			return true;
		}
		return false;
	}


	/**
	 * Update news recived from seosamba
	 *
	 * @param array $news
	 * @return UPDATER_SUCCESS if update wents well or UPDATER_FAIL if not
	 */
	public function updateNews($news) {
		if(empty($news)) {
			return self::UPDATER_SUCCESS;
		}
		if(isset($news->newsfolder)) {
			$result = $this->_model->saveNewsFolder($news->newsfolder);
			if($result) {
				unset($news->newsfolder);
			}
		}
		$this->_model->cleanNews();
		foreach ($news as $newsCategory) {
			if(empty($newsCategory->name)) {
				continue;
			}
			$nocat = ($newsCategory->name === 'nocategory');
			if(!$nocat) {
				$rcmsNewCategoryId = $this->_model->saveNewsCategory($newsCategory->name);
				if(!is_numeric($rcmsNewCategoryId)) {
					return self::UPDATER_FAIL;
				}
			}
			if(isset ($newsCategory->newslist)) {
				foreach ($newsCategory->newslist as $newsPage) {
					$rcmsNewsPage = new RCMS_Object_News_News();
					$rcmsNewsPage->setIdNewsCategory(($nocat) ? $newsCategory->id : $rcmsNewCategoryId);
					$rcmsNewsPage->setNewsUrl($newsPage->url);
					$rcmsNewsPage->setTitle($newsPage->headerTitle);
					$rcmsNewsPage->setText($newsPage->content);
					$rcmsNewsPage->setIntro($newsPage->description);
					$rcmsNewsPage->setDate(date("Y-m-d H:i:s", $newsPage->date));
					$rcmsNewsPage->setOrder($newsPage->order);
					$rcmsNewsPage->setMetaDescription($newsPage->metaDescription);
					$rcmsNewsPage->setMetaKeywords($newsPage->metaKeywords);
					$rcmsNewsPage->setIsFeatured($newsPage->isFeatured);
					$newsSaveResultId = $rcmsNewsPage->save();
					if(!is_numeric($newsSaveResultId)) {
						return self::UPDATER_FAIL;
					}
				}
			}
		}
		$this->_seoParser->syncNewsRoutes();
		return self::UPDATER_SUCCESS;
	}

	public function updateNewsSitemap($newsSitemapContent) {
		if(empty ($newsSitemapContent)) {
			return self::UPDATER_SUCCESS;
		}
		$saveResult = RCMS_Tools_FilesystemTools::saveFile($this->_websitePath . 'public/sitemapnews.xml', $newsSitemapContent);
		if($saveResult) {
			return self::UPDATER_SUCCESS;
		}
	}

	/**
	 * Saving or updating sitemapinde.xml that system recives from seosamba
	 *
	 * @param string $indexSitemap
	 * @return string
	 */
	public function updateIndexSitemap($indexSitemap) {
		if(empty ($indexSitemap)) {
			return self::UPDATER_SUCCESS;
		}
		try {
			RCMS_Tools_FilesystemTools::saveFile($this->_websitePath . 'public/sitemapindex.xml', $indexSitemap);
		}
		catch (Exception $e) {
			return self::UPDATER_FAIL;
		}
		return self::UPDATER_SUCCESS;
	}

	/**
	 * Update the rss feeds
	 *
	 * @param array $rssFeeds
	 * @return mixed one of Updater constants (RSSFEEDS_EMPTY_ERROR, UPDATER_SUCCESS, UPDATER_FAIL)
	 */
	public function updateRssFeeds($rssFeeds) {
		if(empty($rssFeeds)) {
			return self::UPDATER_SUCCESS;
		}
		$allsaveResult = RCMS_Tools_FilesystemTools::saveFile($this->_websitePath . 'public/all.xml', $rssFeeds->all);
		$fullSaveResult = RCMS_Tools_FilesystemTools::saveFile($this->_websitePath . 'public/full.xml', $rssFeeds->full);
		if(!empty ($rssFeeds->categories)) {
			foreach ($rssFeeds->categories as $rssFeedCatName => $rssFeedCatContent) {
				RCMS_Tools_FilesystemTools::saveFile($this->_websitePath . 'public/' . $rssFeedCatName . '.xml', $rssFeedCatContent);
			}
		}
		if($fullSaveResult && $allsaveResult) {
			return self::UPDATER_SUCCESS;
		}
		return self::UPDATER_FAIL;
	}

	/**
	 * Update cms by recived variables
	 *
	 * @param array $vars contains objects with name and code properties
	 * @return string
	 */
	public function updateVariables($vars) {
		if(empty ($vars)) {
			return self::UPDATER_SUCCESS;
		}
		$this->_model->cleanVars();
		foreach ($vars as $variable) {
			$this->_model->saveVariables($variable->name, $variable->code);
		}
		return self::UPDATER_SUCCESS;
	}


	public function updateSeoVars($seoData) {
		if(empty($seoData)) {
			return self::UPDATER_SUCCESS;
		}
		$this->_model->cleanSeoData();
		foreach ($seoData as $seoPerPage) {
			$this->_model->saveSeoData($seoPerPage->seo_top, $seoPerPage->seo_bottom, $seoPerPage->rcms_pid);
		}
		return self::UPDATER_SUCCESS;
	}

	public function updateVerification($data) {
		if(empty($data)) {
			return self::UPDATER_SUCCESS;
		}
		try {
			$result = RCMS_Tools_FilesystemTools::saveFile($this->_websitePath . 'public/'. $data->fileName, $data->fileContent);
		}
		catch (Exception $e) {
			return self::UPDATER_FAIL;
		}
		return self::UPDATER_SUCCESS;
	}

	public function updateServices($servicesContent) {
		$result = $this->_model->updateServicesContent($servicesContent);
		if($result) {
			return self::UPDATER_SUCCESS;
		}
	}


	/**
	 * Saving grubbed pages from old website
	 *
	 * @param array $grubbedData
	 */
	public function saveGrubbedPages($grubbedData) {
		$this->_cleanBeforeGrubbing();
		//checking that category doesn't exists
		if(($importedCategoryId = $this->_checkCategory('Imported Pages')) === false) {
			//creating "Imported Pages" category
			$importedCategoryId = $this->_createCategory('Imported Pages');
		}
		//get default template id
		$templateId = $this->_model->getTemplateIdByName('default');
		foreach ($grubbedData as $grubbedPageData) {
			$parsedGrubbedUrl = parse_url($grubbedPageData['url']);
			if($parsedGrubbedUrl['path'] == '/') {
				continue;
			}
			$grubbedPageData['title'] = strip_tags($grubbedPageData['title']);
			$grubbedPageData['content'] = strip_tags($grubbedPageData['content']);
			$oldUrl = trim($parsedGrubbedUrl['path'], '/');
			$newCategoryId = $this->_model->insertCategory($grubbedPageData['title'], $importedCategoryId);
			$importedPage = new RCMS_Object_Page_Page();
			$importedPage->setCategoryId($newCategoryId);
			$importedPage->setH1Tag($grubbedPageData['title']);
			$importedPage->setUrl(strtolower(preg_replace('/[#?\s\&\@\!\$\%\^\*\(\)\+\/\<\>\:\"\{\}\[\]\,\.\;\|]+/', '-', strip_tags($grubbedPageData['title']))));
			$importedPage->setHeaderTitle($grubbedPageData['title']);
			$importedPage->setNavName($grubbedPageData['title']);
			$importedPage->setMetaDescription($grubbedPageData['content']);
			$importedPage->setShortDescription($grubbedPageData['content']);
			$importedPage->setShowInMenu(RCMS_Object_Page_Page::SHOW_IN_MAIN_MENU);
			$importedPage->setLastUpdate(date("Y-m-d H:i:s"));
			$importedPage->setTemplateId($templateId);
			$pageId = $importedPage->save();
			if(str_replace('.html', '', $oldUrl) != $importedPage->getUrl()) {
				$this->_seoParser->chainSyncOnUpdate($oldUrl, $importedPage->getUrl(), $importedPage->getH1Tag(), $pageId);
			}
		}
	}

	private function _checkCategory($categoryName) {
		$result = $this->_model->checkCategory($categoryName);
		if(!empty($result) && isset($result['id'])) {
			return $result['id'];
		}
		return false;
	}

	private function _createCategory($categoryName) {
		$catId = $this->_model->insertCategory($categoryName);
		$templateId = $this->_model->getTemplateIdByName('category');
		$catPage = new RCMS_Object_Page_Page();
		$catPage->setCategoryId($catId);
		$catPage->setNavName($categoryName);
		$catPage->setUrl(strtolower(str_replace(' ', '-', $categoryName)));
		$catPage->setHeaderTitle($categoryName);
		$catPage->setTemplateId($templateId);
		$catPage->setShowInMenu(RCMS_Object_Page_Page::SHOW_IN_MAIN_MENU);
		$catPage->setH1Tag($categoryName);
		$catPage->setLastUpdate(date("Y-m-d H:i:s"));
		$catPage->save();
		return $catId;
	}

	private function _cleanBeforeGrubbing() {
		$importedCategoryId = $this->_checkCategory('Imported Pages');
		if(!$importedCategoryId) {
			return;
		}
		$pagesIds = $this->_model->getCategoryPagesIds($importedCategoryId);
		$idsSet = rtrim(implode(',', $pagesIds), ',');
		$this->_model->cleanGrubbed301s($idsSet);
		$this->_model->cleanGrubbedPages($idsSet);
		$this->_model->cleanCategories($importedCategoryId);
		$this->_model->cleanImportedCategory($importedCategoryId);
	}
}

